package org.zwd.computePrice.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.zwd.computePrice.dao.CrabPriceDao;
import org.zwd.computePrice.dao.DBUtils;
import org.zwd.computePrice.dao.TempDao;
import org.zwd.computePrice.dao.UserDao;
import org.zwd.computePrice.domain.Crab;
import org.zwd.computePrice.domain.CrabPrice;
import org.zwd.computePrice.domain.Temp;
import org.zwd.computePrice.domain.User;

public class TempService {
	private Connection conn;
	private UserDao userDao = new UserDao();
	private TempDao tempDao = new TempDao();
	private CrabPriceDao crabPriceDao = new CrabPriceDao();
	public void  createTemp(List<Crab> crabList,String name,int userid,int isOrder){
		try {
			conn = DBUtils.getConnection();
			conn.setAutoCommit(false);
			Temp temp = new Temp();
			temp.setClientName(name);
			User user = userDao.findUserByid(userid);
			temp.setUser(user);
			temp.setIsOrder(isOrder);
			int num = tempDao.insertTemp(conn,temp);
			for(Crab crab : crabList){
				//重新赋予价格
				CrabPrice crabPrice = crabPriceDao.loadPrice(crab.getId(),isOrder);
				crab.setCrabPrice(crabPrice);
				tempDao.insertTempItem(conn, num, crab);
			}
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void deleteItemByid(int itemid){
		try {
			conn = DBUtils.getConnection();
			conn.setAutoCommit(false);
			
			tempDao.deleteOrderItemByid(conn, itemid);
			tempDao.deleteOrderByid(conn, itemid);
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public List<Temp> LoadAllTemp(int isOrder){
		return tempDao.findAllTemp(isOrder);
	}
	
	public List<Crab> findCrabsByTempid(int tempid){
		return tempDao.findCrabByTempId(tempid);
	}
	
	public Temp findTempByTempid(int tempid,int isOrder){
		Temp temp = tempDao.findTempByid(tempid);
		List<Crab> crabList = tempDao.findCrabByTempId(temp.getId());
		for(Crab crab : crabList){
			CrabPrice crabPrice = crabPriceDao.loadPrice(crab.getId(),isOrder);
			crab.setCrabPrice(crabPrice);
		}
		temp.setCrabList(crabList);
		return temp;
	}
}
